<?php

namespace App\Models;

use App\Enums\GoodsBusinessEnum;
use App\Enums\GoodsOpenSaleEnum;
use App\Exceptions\ApiErrorException;
use App\Exceptions\ApiException;
use App\Services\CommonService;
use App\Services\GoodsService;
use App\Traits\ModelEventTrait;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\DB;

class Goods extends BaseModel
{
    use HasFactory;
    use ModelEventTrait;

    protected $table = 'sp_goods_2'; //表名
    protected $primaryKey = 'id'; //主键

    const GUESS_LIKE_KEY = 'guess_like_goods';

    //status状态 1上架 2下架 3申请下架 4申请下架拒绝 5违规下架
    const GOODS_STATUS_UP = 1;//上架
    const GOODS_STATUS_DOWN = 2;//下架
    const GOODS_STATUS_APPLY_DOWN = 3;//申请下架
    const GOODS_STATUS_APPLY_DOWN_REFUSE = 4;//申请下架拒绝
    const GOODS_STATUS_ILLEGAL_DOWN = 5;//违规下架

    //is_delete是否删除   1是 2否
    const GOODS_IS_DELETE = 1;//是
    const GOODS_NOT_DELETE = 2;//否

    // public $timestamps = false;
    const CREATED_AT = 'create_time';
    const UPDATED_AT = 'update_time';
    const DELETED_AT = 'delete_time';

    protected $guarded = [];

    protected $casts = [
        'create_time' => 'datetime:Y-m-d H:i:s',
        'update_time' => 'datetime:Y-m-d H:i:s',
    ];

    protected $appends = [
        'imgurl_full',
        'slide_images',
        'position_img_full',
        'business_type_name'
    ];

    public function getBusinessTypeNameAttribute()
    {
        return GoodsBusinessEnum::getNameByKey($this->business_type);
    }
    public function goodsBrandInfo()
    {
        return $this->hasOne(BrandModel::class, BrandModel::KEY, 'brand_id')->select('id','name');
    }

    public function goodsClassInfo()
    {
        return $this->hasOne(GoodsClass::class, GoodsClass::KEY, 'category_id')->select('id','name');
    }
    public function goodsTypeInfo()
    {
        return $this->hasOne(GoodsType::class, GoodsType::KEY, 'goods_type')->select('id','name');
    }
    public function shopInfo()
    {
        return $this->hasOne(ShopUser::class, 'member_id', 'member_id')->select('member_id','shopname');
    }


    public function goods_class()
    {
        return $this->hasOne(GoodsClass::class, GoodsClass::KEY, 'category_id');
    }

    public function goods_type()
    {
        return $this->hasOne(GoodsType::class, GoodsType::KEY, 'goods_type');
    }

    public function brand()
    {
        return $this->hasOne(BrandModel::class, BrandModel::KEY, 'brand_id');
    }

    public function shop()
    {
        return $this->hasOne(ShopUser::class, 'member_id', 'member_id');
    }

    public function goods_depict()
    {
        return $this->hasOne(GoodsDepict::class, 'goods_id', 'id');
    }

    /**
     * 关联商品规格表
     * @return \Illuminate\Database\Eloquent\Relations\HasMany
     */
    public function rentSkuList()
    {
        return $this->hasMany(GoodsRentSku::class,'goods_id','id')
            ->with('goodsRentSkuMealValue')
            ->select('goods_sku_id','goods_id','goods_sku_no','buyout_price','stock_num','goods_props','spec_value_ids','meal_value_ids','meal_id','off_sale','id')
            ->orderBy('id', 'asc');
    }
    public function skuList()
    {
        return $this->hasMany(GoodsSku::class,'goods_id','id')
            ->select('goods_sku_id','goods_id','goods_sku_no','stock_num','goods_price','line_price','goods_props','spec_value_ids','off_sale','id')
            ->orderBy('id', 'asc');
    }
    public function apiRentSkuList()
    {
        return $this->hasMany(GoodsRentSku::class,'goods_id','id')
            ->where('off_sale',0)
            ->with('goodsRentSkuMealValue')
            ->select('goods_sku_id','goods_id','goods_sku_no','buyout_price','stock_num','goods_props','spec_value_ids','meal_value_ids','meal_id','off_sale','id')
            ->orderBy('id', 'asc');
    }
    public function getImgurlFullAttribute()
    {
        if (empty($this->imgurl)) {
            return '';
        }
        return config('alipay.oss.imgHost') . $this->imgurl;
    }
    public function getPositionImgFullAttribute()
    {
        if (empty($this->position_img)) {
            return '';
        }
        return config('alipay.oss.imgHost') . $this->position_img;
    }

    public function getSlideImagesAttribute()
    {
        if (empty($this->carousel_images)) {
            return '';
        }
        $carousel_images = explode(',',$this->carousel_images);
        $imgs=[];
        foreach ($carousel_images as $imgurl){
            $imgs[]=config('alipay.oss.imgHost') . $imgurl;
        }
        return $imgs;
    }

    //获取配送方式 $type 1寄出 2归还
    public static function conveyType($type,$convey_type){
        if (empty($type)){
            return '';
        }
        if($type == 1){
            $convey_type1 = array(1 => '包邮', 2 => '到付(自付)', 3 => '到店自取');
            return $convey_type1[$convey_type];
        }else{
            $convey_type2 = array(1 => '包邮', 2 => '到付(自付)', 3 => '无');
            return $convey_type2[$convey_type];
        }
    }

    //根据id查询商品详情信息
    protected function GetGoodsDetailsDataById($id)
    {
        $select = array('g.id as goods_id', 'g.member_id', 'g.status', 'g.title', 'g.spread_title', 'g.new_grade', 'g.rent_label',
            'g.convey_type',
            'gd.images', 'gd.goods_attribute', 'gd.goods_content', 'su.shopname', 'su.photo', 'su.shoptype', 'su.is_show', 'c.name');
        $data = $this
            ->from('sp_goods_2 as g')
            ->select($select)
            ->leftjoin('sp_goods_depict_2 as gd', 'gd.goods_id', '=', 'g.id')
            ->leftjoin('sp_shop_user_2 as su', 'su.member_id', '=', 'g.member_id')
            ->leftjoin('sp_category as c', 'c.id', '=', 'su.shoptype')
            ->where([['g.id', $id],['g.is_delete',GoodsService::GOODS_NO_DELETE_STATUS]])
            ->first();
        $data = $data ? $data->toArray() : array();
        return $data;
    }

    //根据memberid查询店铺商品信息
    protected function GetGoodsDataByMemberid($pageSize, $member_id)
    {
        $where = array(
            'status' => 1,
            'ischeck' => 1,
            'member_id' => $member_id,
            'is_delete' => GoodsService::GOODS_NO_DELETE_STATUS,
        );
        $data = $this->where($where)->paginate($pageSize);
        $data = $data ? $data->toArray() : array();
        return $data;
    }

    //获取商品
    protected function getGoods($pageSize, $where, $orwhere)
    {
        $data = $this
            ->from('sp_goods_2 as g')
            ->leftjoin('sp_category as c','c.id','=','g.category_id')
            ->select('g.id','g.title','g.imgurl','c.name as cate_name')
            ->where($where)
            ->orWhere($orwhere)
            ->orderBy('id', 'desc')
            ->paginate($pageSize);
        $data = $data ? $data->toArray() : array();
        return $data;
    }

    //搜索商品列表
    protected function getSearchGoodsList($pageSize, $where, $orderby, $upanddown)
    {
        $select = array('id', 'category_id', 'title', 'imgurl', 'new_grade', 'rent_label', 'is_huabei', 'min_price', 'min_lease_term');
//        if (!empty($min_price)) {
//            $min_price = explode('-', $min_price);
//            $data = $this
//                ->select($select)
//                ->where($where)
//                ->whereBetween('min_price', $min_price)
//                ->orderBy($orderby, $upanddown)
//                ->paginate($pageSize);
//        } else {
            $data = $this
                ->select($select)
                ->where($where)
                ->orderBy($orderby, $upanddown)
                ->paginate($pageSize);
//        }
        $data = $data ? $data->toArray() : array();
        return $data;
    }

    //根据id修改
    protected function editDataById($id, $data)
    {
        $where = array(
            'id' => $id,
        );
        return $data = $this->where($where)->update($data);
    }

    //pc分类页获取商品列表
    protected function GetGoodsList($where,$wherein,$search_name,$page, $pageSize)
    {
        if($wherein && $search_name){
            $data = $this->where($where)->wherein('category_id',$wherein)
                ->where(function($query) use ($search_name){
                    $query->where('new_grade', 'like', "%{$search_name}%")
                        ->orWhere('title','like','%'.$search_name.'%')
                        ->orWhere('rent_label','like','%'.$search_name.'%');
                })
                ->select('id', 'category_id','title', 'new_grade', 'imgurl','status','min_price')
                ->orderBy('isrecommand', 'asc')
                ->paginate($pageSize);
        }elseif ($search_name && !$wherein){
            $data = $this->where($where)
                ->where(function($query) use ($search_name){
                    $query->where('new_grade', 'like', "%{$search_name}%")
                        ->orWhere('title','like','%'.$search_name.'%')
                        ->orWhere('rent_label','like','%'.$search_name.'%');
                })
                ->select('id','category_id', 'title', 'new_grade', 'imgurl','status','min_price')
                ->orderBy('isrecommand', 'asc')
                ->paginate($pageSize);
        }elseif (!$search_name && $wherein){
            $data = $this->where($where)
                ->wherein('category_id',$wherein)
                ->select('id','category_id', 'title', 'new_grade', 'imgurl','status','min_price')
                ->orderBy('isrecommand', 'asc')
                ->paginate($pageSize);
        }else{
            $data = $this->where($where)
                ->select('id','category_id', 'title', 'new_grade', 'imgurl','status','min_price')
                ->orderBy('isrecommand', 'asc')
                ->paginate($pageSize);
        }
        $data = $data ? $data->toArray() : array();
        return $data;
    }

    protected function GetGoodsListAndCategory($where, $goods_name, $page=1, $pageSize)
    {
        if($goods_name){
            $data = $this->from('sp_goods_2 as g')->where($where)
                ->where(function($query) use ($goods_name){
                    $query->where('g.title', 'like', "%{$goods_name}%")->orWhere('g.id',$goods_name);
                })
                ->leftjoin('sp_goods_class as c', 'c.id', '=', 'g.subclass_id')
                ->leftjoin('sp_shop_user_2 as s', 'g.member_id', '=', 's.member_id')
                ->select('g.id as goods_id', 'g.title', 'g.imgurl','g.goods_type','g.min_price as price','s.shopname','g.min_lease_term')
                ->orderBy('g.goods_sort', 'asc')
                ->orderBy('g.id', 'desc')
                ->paginate($pageSize);
        }else{
            $data = $this->from('sp_goods_2 as g')->where($where)
                ->leftjoin('sp_goods_class as c', 'c.id', '=', 'g.subclass_id')
                ->leftjoin('sp_shop_user_2 as s', 'g.member_id', '=', 's.member_id')
                ->select('g.id as goods_id', 'g.title', 'g.imgurl','g.goods_type','g.min_price as price','c.name as cate_name','s.shopname','g.min_lease_term')
                ->orderBy('g.goods_sort', 'asc')
                ->orderBy('g.id', 'desc')
                ->paginate($pageSize);
        }
        $data = $data ? $data->toArray() : array();
        foreach ($data['data'] as $key=>&$value) {
            $value['min_lease_term'] = GoodsRentSku::query()->from('sp_goods_rent_sku as sku')->where('goods_id', $value['goods_id'])
                ->leftJoin('sp_goods_rent_sku_meal as rm', 'rm.goods_sku_id', '=', 'sku.id')
                ->leftJoin('sp_goods_rent_meal_value as mv', 'mv.meal_value_id', '=', 'rm.meal_value_id')
                ->orderBy('mv.meal_value', 'desc')
                ->value('mv.meal_value');
        }

        return $data;
    }

    //草稿箱
    protected function GoodsDraft($request,$member_id=''){
        $pageSize = !empty($request['pageSize'])?$request['pageSize']:CommonService::PAGESIZE;
        if(!empty($request['goods_name'])){
            $where[] = ['g.title','like','%'.trim($request['goods_name']).'%'];
        }
        if(!empty($request['goods_id'])){
            $where[] = ['g.id',trim($request['goods_id'])];
        }
        if($member_id){
            $where[] = ['g.member_id',$member_id];
            $where_count[] = ['g.member_id',$member_id];
        }
        $where[] = ['g.ischeck',GoodsService::GOODS_CHECK_STATUS_DRAFT];
        $where[] = ['g.is_delete',GoodsService::GOODS_NO_DELETE_STATUS];
        $where_count[] = ['g.is_delete',GoodsService::GOODS_NO_DELETE_STATUS];
        $draft = $this->from('sp_goods_2 as g')->where($where)->count();
        $list = $this->from('sp_goods_2 as g')->where($where)
            ->leftjoin('sp_category as c','c.id','=','g.category_id')
            ->leftjoin('sp_other_admin as u','u.id','=','g.uid')
            ->select('g.id','g.title','c.name as cate_name','g.update_time','u.username')
            ->orderBy('g.goods_sort', 'asc')
            ->orderBy('g.id', 'desc')
            ->paginate($pageSize);

        $status_put = $this->from('sp_goods_2 as g')->where($where_count)->wherein('g.status',[GoodsService::GOODS_STATUS_PUT,GoodsService::GOODS_STATUS_APPLY_OFF])->count();
        $status_off = $this->from('sp_goods_2 as g')->where($where_count)->wherein('g.status',[GoodsService::GOODS_STATUS_OFF,GoodsService::GOODS_STATUS_VIOLATION_OFF])->count();
        $status_check = $this->from('sp_goods_2 as g')->where($where_count)->Where('g.ischeck',GoodsService::GOODS_CHECK_STATUS_NO)->orWhere([['g.ischeck',GoodsService::GOODS_CHECK_STATUS_REFUSE],['g.status',GoodsService::GOODS_STATUS_APPLY_OFF],['g.status',GoodsService::GOODS_STATUS_OFF_REFUSE]])->count();

        $list = $list ? $list->toArray() : array();
        $list['count']['status_put'] = $status_put;
        $list['count']['status_off'] = $status_off;
        $list['count']['status_check'] = $status_check;
        $list['count']['draft'] = $draft;
        return $list;
    }

    //管理后台商品列表
    protected function AdminGoodsList($request){
        $where = [];
        $pageSize = !empty($request['pageSize'])?$request['pageSize']:CommonService::PAGESIZE;
        if(!empty($request['goods_name'])){
            $where[] = ['g.title','like','%'.trim($request['goods_name']).'%'];
        }
        if(!empty($request['shop_name'])){
            $where[] = ['s.shopname','like','%'.trim($request['shop_name']).'%'];
        }
        if(!empty($request['cate_id'])){
            $pid=GoodsClass::query()->where('id',$request['cate_id'])->value('pid');
            if($pid>0){
                $where[] = ['g.subclass_id',$request['cate_id']];
            }else{
                $where[] = ['g.category_id',$request['cate_id']];
            }
        }
        if(!empty($request['rent_type'])){
            $where[] = [$request['rent_type']];
        }
        if(!empty($request['create_time'])){
            $time_data = searchTime($request['create_time']);
            $begin_time = $time_data['begin_time'];
            $end_time = $time_data['end_time'];
            $where[] = ['g.create_time','>=',strtotime($begin_time)];
            $where[] = ['g.create_time','<=',strtotime($end_time)];
        }
        $where0[] = ['g.is_delete',GoodsService::GOODS_NO_DELETE_STATUS];
        //$where0[] = ['g.status','>=',GoodsService::GOODS_STATUS_PUT];

        $request['goods_status'] = !empty($request['goods_status'])?$request['goods_status']:GoodsService::GOODS_PUT_LIST;
        if(!empty($request['goods_status']) && $request['goods_status'] == GoodsService::GOODS_PUT_LIST){
            $status_where[] = ['g.status', GoodsService::GOODS_STATUS_PUT];
            $where = array_merge($where,$where0);
            $list = $this->with(['goodsBrandInfo','goodsClassInfo','goodsTypeInfo'])->from('sp_goods_2 as g')->where($where)->where($status_where)
                ->leftjoin('sp_shop_user_2 as s','s.member_id','=','g.member_id')
                ->select('g.id','g.title','g.status','g.goods_type','g.brand_id','g.category_id','g.goods_sort','g.subclass_id','g.imgurl','g.new_grade','g.business_type','g.create_time','g.update_time','s.shopname','g.min_lease_term')
                ->orderBy('g.goods_sort', 'asc')
                ->orderBy('g.id', 'desc')
                ->paginate($pageSize);
        }else{
            $status_where_in = [GoodsService::GOODS_STATUS_OFF,GoodsService::GOODS_STATUS_VIOLATION_OFF];
            $where = array_merge($where,$where0);
            $list = $this->from('sp_goods_2 as g')->with(['goodsBrandInfo','goodsClassInfo','goodsTypeInfo'])->where($where)->whereIn('g.status',$status_where_in)
                ->leftjoin('sp_shop_user_2 as s','s.member_id','=','g.member_id')
                ->select('g.id','g.title','g.status','g.goods_type','g.brand_id','g.category_id','g.goods_sort','g.subclass_id','g.imgurl','g.new_grade','g.business_type','g.create_time','g.update_time','s.shopname','g.min_lease_term')
                ->orderBy('g.goods_sort', 'asc')
                ->orderBy('g.id', 'desc')
                ->paginate($pageSize);
        }

        if($request['goods_status'] && $request['goods_status'] != GoodsService::GOODS_PUT_LIST){
            $where2 = $where0;
        }elseif ($request['goods_status'] && $request['goods_status'] == GoodsService::GOODS_PUT_LIST){
            $where2 = array_merge($where,$where0);
        }
        unset($status_where);
        $status_where[] = ['g.status', GoodsService::GOODS_STATUS_PUT];
        $status_put = $this->from('sp_goods_2 as g')->where($where2)->where($status_where)
            ->leftjoin('sp_shop_user_2 as s','s.member_id','=','g.member_id')->leftjoin('sp_category as c','c.id','=','g.category_id')->count();

        unset($status_where);
        $status_where_in = [GoodsService::GOODS_STATUS_OFF,GoodsService::GOODS_STATUS_VIOLATION_OFF];
        $status_off = $this->from('sp_goods_2 as g')->where($where2)->whereIn('g.status',$status_where_in)
            ->leftjoin('sp_shop_user_2 as s','s.member_id','=','g.member_id')->leftjoin('sp_category as c','c.id','=','g.category_id')->count();


        $list = $list ? $list->toArray() : array();
        $list['count']['status_put'] = $status_put;
        $list['count']['status_off'] = $status_off;
        return $list;
    }


    //供应商后台商品列表
    protected function goodsList($request,$member_id=''){
        $where = [];
        $orwhere = [];
        $status = [];
        $where1 = [];
        $pageSize = !empty($request['pageSize'])?$request['pageSize']:CommonService::PAGESIZE;
        if(!empty($request['goods_name'])){
            $where[] = ['g.title','like','%'.trim($request['goods_name']).'%'];
        }
        if(!empty($request['shop_name'])){
            $where[] = ['s.shopname','like','%'.trim($request['shop_name']).'%'];
        }
        if(!empty($request['cate_id'])){
            $where[] = ['g.category_id',$request['cate_id']];
        }
        if(!empty($request['rent_type'])){
            $where[] = [$request['rent_type']];
        }
        if(!empty($request['create_time'])){
            $time_data = searchTime($request['create_time']);
            $begin_time = $time_data['begin_time'];
            $end_time = $time_data['end_time'];
            $where[] = ['g.create_time','>=',strtotime($begin_time)];
            $where[] = ['g.create_time','<=',strtotime($end_time)];
        }
        if($member_id){
            $where0[] = ['g.member_id',$member_id];
        }
        $where0[] = ['g.is_delete',GoodsService::GOODS_NO_DELETE_STATUS];

        if(!empty($request['goods_status'])){
            $where = array_merge($where,$where0);

            if($request['goods_status'] &&$request['goods_status'] == GoodsService::GOODS_PUT_LIST || $request['goods_status'] == GoodsService::GOODS_OFF_LIST){
                if($request['goods_status'] == GoodsService::GOODS_PUT_LIST){
                    $status = [GoodsService::GOODS_STATUS_PUT,GoodsService::GOODS_STATUS_APPLY_OFF];
                }elseif ($request['goods_status'] == GoodsService::GOODS_OFF_LIST){
                    $status = [GoodsService::GOODS_STATUS_OFF,GoodsService::GOODS_STATUS_VIOLATION_OFF];
                }
                $list = $this->from('sp_goods_2 as g')->where($where)->wherein('g.status',$status)
                    ->leftjoin('sp_shop_user_2 as s','s.member_id','=','g.member_id')
                    ->leftjoin('sp_category as c','c.id','=','g.category_id')
                    ->select('g.id','g.title','g.status','g.displayorder','g.imgurl','c.name as cate_name','g.ischeck','g.create_time','g.check_reason','s.shopname','g.activity_type','g.checked_status')
                    ->orderBy('g.goods_sort', 'asc')
                    ->orderBy('g.id', 'desc')
                    ->paginate($pageSize);
            }elseif($request['goods_status'] && $request['goods_status'] == GoodsService::GOODS_CHECK_LIST){
                if(!empty($request['check_type']) && empty($request['check_status'])){
                    if($request['check_type'] == GoodsService::GOODS_CHECK_TYPE){//商品审核
                        $orwhere = function($query){
                            $query->orwhere(function($query){
                                $query->whereIn('g.ischeck',[GoodsService::GOODS_CHECK_STATUS_NO,GoodsService::GOODS_CHECK_STATUS_REFUSE]);
                            });
                        };
                    }elseif ($request['check_type'] == GoodsService::GOODS_OFF_CHECK_TYPE){//下架审核
                        $orwhere = function($query){
                            $query->orwhere(function($query){
                                $query->whereIn('g.status',[GoodsService::GOODS_STATUS_APPLY_OFF,GoodsService::GOODS_STATUS_OFF_REFUSE]);
                            });
                        };
                    }
                }elseif(!empty($request['check_status']) && empty($request['check_type'])){
                    if($request['check_status'] == GoodsService::GOODS_NO_CHECK_STATUS){//未审核
                        $orwhere = function($query){
                            $query->orwhere(function($query){
                                $query->where('g.ischeck',GoodsService::GOODS_CHECK_STATUS_NO);
                            })->orwhere(function($query){
                                $query->where('g.status',GoodsService::GOODS_STATUS_APPLY_OFF);
                            });
                        };
                    }elseif ($request['check_status'] == GoodsService::GOODS_REFUSE_CHECK_STATUS){//审核未通过
                        $orwhere = function($query){
                            $query->orwhere(function($query){
                                $query->where('g.ischeck',GoodsService::GOODS_CHECK_STATUS_REFUSE);
                            })->orwhere(function($query){
                                $query->where('g.status',GoodsService::GOODS_STATUS_OFF_REFUSE);
                            });
                        };
                    }
                }elseif(!empty($request['check_status']) && !empty($request['check_type'])){
                    if($request['check_type'] == GoodsService::GOODS_CHECK_TYPE){//商品审核
                        if($request['check_status'] == GoodsService::GOODS_NO_CHECK_STATUS){//未审核
                            $where1[] = ['g.ischeck',GoodsService::GOODS_CHECK_STATUS_NO];
                            $where = array_merge($where,$where1);
                        }elseif ($request['check_status'] == GoodsService::GOODS_REFUSE_CHECK_STATUS){//审核未通过
                            $where1[] = ['g.ischeck',GoodsService::GOODS_CHECK_STATUS_REFUSE];
                            $where = array_merge($where,$where1);
                        }
                    }elseif ($request['check_type'] == GoodsService::GOODS_OFF_CHECK_TYPE) {//下架审核
                        if($request['check_status'] == GoodsService::GOODS_NO_CHECK_STATUS){//未审核
                            $where2[] = ['g.status',GoodsService::GOODS_STATUS_APPLY_OFF];
                            $where = array_merge($where,$where2);
                        }elseif ($request['check_status'] == GoodsService::GOODS_REFUSE_CHECK_STATUS){//审核未通过
                            $where2[] =  ['g.status',GoodsService::GOODS_STATUS_OFF_REFUSE];
                            $where = array_merge($where,$where2);
                        }
                    }
                }elseif(empty($request['check_status']) && empty($request['check_type'])){
                    $orwhere = function($query){
                        $query->orwhere(function($query){
                            $query->whereIn('g.ischeck',[GoodsService::GOODS_CHECK_STATUS_NO,GoodsService::GOODS_CHECK_STATUS_REFUSE]);
                        })->orwhere(function($query){
                            $query->whereIn('g.status',[GoodsService::GOODS_STATUS_APPLY_OFF,GoodsService::GOODS_STATUS_OFF_REFUSE]);
                        });
                    };
                }
                if(!empty($orwhere)){
                    $list = $this->from('sp_goods_2 as g')
                        ->where($where)
                        ->where($orwhere)
                        ->leftjoin('sp_shop_user_2 as s','s.member_id','=','g.member_id')
                        ->leftjoin('sp_category as c','c.id','=','g.category_id')
                        ->select('g.id','g.title','g.status','g.displayorder','g.imgurl','c.name as cate_name','g.ischeck','g.create_time','g.check_reason','s.shopname','g.activity_type','g.checked_status')
                        ->orderBy('g.goods_sort', 'asc')
                        ->orderBy('g.id', 'desc')
                        ->paginate($pageSize);
                }else{
                    $list = $this->from('sp_goods_2 as g')
                        ->where($where)
                        ->leftjoin('sp_shop_user_2 as s','s.member_id','=','g.member_id')
                        ->leftjoin('sp_category as c','c.id','=','g.category_id')
                        ->select('g.id','g.title','g.status','g.displayorder','g.imgurl','c.name as cate_name','g.ischeck','g.create_time','g.check_reason','s.shopname','g.activity_type','g.checked_status')
                        ->orderBy('g.goods_sort', 'asc')
                        ->orderBy('g.id', 'desc')
                        ->paginate($pageSize);
                }

            }else{
                $list = $this->from('sp_goods_2 as g')->where($where)
                    ->leftjoin('sp_shop_user_2 as s','s.member_id','=','g.member_id')
                    ->leftjoin('sp_category as c','c.id','=','g.category_id')
                    ->select('g.id','g.title','g.status','g.displayorder','g.imgurl','c.name as cate_name','g.ischeck','g.create_time','g.check_reason','s.shopname','g.activity_type','g.checked_status')
                    ->orderBy('g.goods_sort', 'asc')
                    ->orderBy('g.id', 'desc')
                    ->paginate($pageSize);
            }
        }else{
            $list = $this->from('sp_goods_2 as g')->where($where)
                ->leftjoin('sp_shop_user_2 as s','s.member_id','=','g.member_id')
                ->leftjoin('sp_category as c','c.id','=','g.category_id')
                ->select('g.id','g.title','g.status','g.displayorder','g.imgurl','c.name as cate_name','g.ischeck','g.create_time','g.check_reason','s.shopname','g.activity_type','g.checked_status')
                ->orderBy('g.goods_sort', 'asc')
                ->orderBy('g.id', 'desc')
                ->paginate($pageSize);
        }
        $request['goods_status'] = !empty($request['goods_status'])?$request['goods_status']:1;
        if($request['goods_status'] && $request['goods_status'] == GoodsService::GOODS_PUT_LIST){
            $where2 = array_merge($where,$where0);
        }else{
            $where2 = $where0;
        }
        unset($status_where);
        $status_where[] = ['g.ischeck',GoodsService::GOODS_CHECK_STATUS_CHECKED];
        $status_put = $this->from('sp_goods_2 as g')->where($where2)->where($status_where)
            ->wherein('g.status',[GoodsService::GOODS_STATUS_PUT,GoodsService::GOODS_STATUS_APPLY_OFF])
            ->leftjoin('sp_shop_user_2 as s','s.member_id','=','g.member_id')->leftjoin('sp_category as c','c.id','=','g.category_id')->count();
        if($request['goods_status'] && $request['goods_status'] == GoodsService::GOODS_OFF_LIST){
            $where2 = array_merge($where,$where0);
        }else{
            $where2 = $where0;
        }
        unset($status_where);
        $status_where[] = ['g.ischeck','>',GoodsService::GOODS_CHECK_STATUS_DRAFT];
        $status_where[] = ['g.ischeck','!=',GoodsService::GOODS_CHECK_STATUS_NO];
        $status_off = $this->from('sp_goods_2 as g')->where($where2)->where($status_where)
            ->wherein('g.status',[GoodsService::GOODS_STATUS_OFF,GoodsService::GOODS_STATUS_VIOLATION_OFF])
            ->leftjoin('sp_shop_user_2 as s','s.member_id','=','g.member_id')->leftjoin('sp_category as c','c.id','=','g.category_id')->count();
        if($request['goods_status'] && $request['goods_status'] == GoodsService::GOODS_CHECK_LIST){
            if(!empty($orwhere)){
                $status_check = $this->from('sp_goods_2 as g')->where($where2)
                    ->where($orwhere)
                    ->leftjoin('sp_shop_user_2 as s','s.member_id','=','g.member_id')->leftjoin('sp_category as c','c.id','=','g.category_id')->count();
            }else{
                $where2 = array_merge($where,$where0);
                $status_check = $this->from('sp_goods_2 as g')->where($where2)
                    ->leftjoin('sp_shop_user_2 as s','s.member_id','=','g.member_id')->leftjoin('sp_category as c','c.id','=','g.category_id')->count();
            }
        }else{
            $where2 = array_merge($where,$where0);
            $status_check = $this->from('sp_goods_2 as g')->where($where2)
                ->where(function($query){
                    $query->orwhere(function($query){
                        $query->whereIn('g.ischeck',[GoodsService::GOODS_CHECK_STATUS_NO,GoodsService::GOODS_CHECK_STATUS_REFUSE]);
                    })->orwhere(function($query){
                        $query->whereIn('g.status',[GoodsService::GOODS_STATUS_APPLY_OFF,GoodsService::GOODS_STATUS_OFF_REFUSE]);
                    });
                })
                ->leftjoin('sp_shop_user_2 as s','s.member_id','=','g.member_id')->leftjoin('sp_category as c','c.id','=','g.category_id')->count();
        }

        $draft = $this->from('sp_goods_2')->where([['member_id',$member_id],['ischeck',GoodsService::GOODS_CHECK_STATUS_DRAFT],['is_delete',GoodsService::GOODS_NO_DELETE_STATUS]])->count();

        $list = $list ? $list->toArray() : array();
        $list['count']['status_put'] = $status_put;
        $list['count']['status_off'] = $status_off;
        $list['count']['status_check'] = $status_check;
        $list['count']['draft'] = $draft;
        return $list;
    }

    //管理后台查看商品
    protected function rentGoodsMealSpecInfo($id)
    {
        $data = (new static)->with(['rentSkuList','skuList'])->from('sp_goods_2 as g')
            ->select('g.id','g.title','g.open_stock','g.open_sku_no','g.open_line_price','g.open_sale','g.business_type')
            ->where('g.id', $id)
            ->first();
        $data['specList'] =GoodsRentSpecRel::getSpecList($data['id']);
        $data['mealList'] =GoodsRentMealRel::getMealList($data['id']);
        $data=obToArray($data);
        foreach ($data['mealList'] as $key => &$value){
            foreach ($data['rent_sku_list'] as $k => $v){
                if($value['meal_id'] == $v['meal_id']){
                    $value['rent_sku_list'][] = $v;
                }
            }
        }
        return $data;
    }

    protected function apiRentGoodsMealSpecInfo($id)
    {
        $data = (new static)->with(['apiRentSkuList'])
            ->select('id','title')
            ->where('id', $id)
            ->first();
        if(empty($data)){
            throw new ApiException('商品不存在');
        }

        $data['specList'] =GoodsRentSpecRel::getSpecList($data['id']);
        $data['mealList'] =GoodsRentMealRel::getMealList($data['id']);
        $data=obToArray($data);
        foreach ($data['mealList'] as $key => &$value){
            foreach ($data['rent_sku_list'] as $k => $v){
                if($value['meal_id'] == $v['meal_id']){
                    $value['rent_sku_list'][] = $v;
                }
            }
        }
        unset($data['rent_sku_list']);
        return $data;
    }

    //商品详情


    protected function getGoodsInfo($goods_id)
    {
        $data = $this->from('sp_goods_2 as g')
            ->select('g.id','g.title','g.new_grade','g.rent_label','g.spread_title','g.imgurl','g.open_sale',
                'g.discount_first_amount','g.discount_first','g.discount_max_amount','g.discount_max_sub_amount',
                'g.service_name','g.service_dec','g.service_price','g.open_service','g.goods_name',
                'g.category_id','g.goods_sort','g.subclass_id','g.brand_id','g.goods_type','g.position_img','g.open_jump','g.jump_type','g.jump_link',
                'g.discount_type','g.discount_name','g.business_type','g.min_price','g.min_line_price','g.min_lease_term', 'g.convey_type', 'gd.images as carousel_images','gd.goods_content',
                'su.is_show','su.photo','su.shopname','su.member_id','g.is_delete')
            ->leftjoin('sp_goods_depict_2 as gd', 'gd.goods_id', '=', 'g.id')
            ->leftjoin('sp_shop_user_2 as su', 'su.member_id', '=', 'g.member_id')
            ->where([['g.id', $goods_id]])
            ->first();
        return $data;
    }

    //添加商品基础信息
    protected function AddGoodsData($data,$shop_data,$specData=[]){
        // 验证规格值是否合法

        if (!is_array($specData['specList'])){
            throw new ApiException('规格数据不合法');
        }
        if (!is_array($specData['mealList'])){
            throw new ApiException('套餐数据不合法');
        }
        if (!is_array($specData['rentSkuList'])){
            throw new ApiException('套餐数据不合法');
        }
        if(!isset($specData['rentSkuList'][0]['rentPrices'])||!is_array($specData['rentSkuList'][0]['rentPrices'])){
            throw new ApiException('套餐数据不合法');
        }


        GoodsRentSpec::checkSpecData($specData['specList']);
        GoodsRentMeal::checkMealData($specData['mealList'],$data['business_type']);
        GoodsRentSku::checkSkuData($specData['rentSkuList']);
        $pid=GoodsClass::query()->where('id',$data['category_id'])->value('pid');
        if($pid>0){
            $data['subclass_id']=$data['category_id'];
            $data['category_id']=$pid;
        }else{
            $data['subclass_id']=0;
        }
        $GoodsDepict=$data;
        unset($data['carousel_img']);
        unset($data['goods_content']);
        $data['is_delete'] = Goods::GOODS_NOT_DELETE;
        $data['ischeck'] = GoodsService::GOODS_CHECK_STATUS_DRAFT;
        $data['checked_status'] = !empty($request['status'])?$request['spread_title']:GoodsService::GOODS_STATUS_OFF;
        $data['status'] = !empty($request['status'])?$request['spread_title']:GoodsService::GOODS_STATUS_OFF;
        $data['member_id'] =$shop_data?$shop_data['member_id']:$data['member_id'];
        $goods_res=$this->insertAndGetId($data);
        if($goods_res){
             GoodsDepict::AddGoodsDepict($goods_res,$GoodsDepict['carousel_img'],$GoodsDepict['goods_content']);
            $data['goods_id'] =$goods_res;
            $data['specData'] =$specData;
            self::addGoodsMealSpecData($data);
            return ['status'=>CommonService::HTTP_CODE_SUCCESS,'msg'=>'添加成功','data'=>['goods_id'=>$goods_res]];
        }else{
            return ['status'=>CommonService::HTTP_CODE_FAIL,'msg'=>'添加失败','data'=>[]];
        }
    }

    protected function addGoodsMealSpecData($data){
        // 生成多规格数据 (携带id)
        $spec_data=[];
        $spec_data['newSpecList'] = GoodsRentSpec::getNewSpecList($data['specData']['specList']);
        $spec_data['newMealList'] = GoodsRentMeal::getNewMealList($data['specData']['mealList']);

        // 生成skuList (携带goods_sku_id)
        $spec_data['newRentSkuList'] = GoodsRentSku::getNewSkuList($spec_data['newSpecList'],$spec_data['newMealList'], $data['specData']['rentSkuList']);

        if($data['open_sale']==GoodsOpenSaleEnum::OPEN()->getKey()){
            $spec_data['newSkuList'] = GoodsSku::getNewSkuList($spec_data['newSpecList'],$data['specData']['skuList']);
        }

        // 更新商品
        return  DB::transaction(function () use ($data,$spec_data) {
            // 新增商品与规格关联
            GoodsRentSpecRel::updates((int)$data['goods_id'], $spec_data['newSpecList']);
            GoodsRentMealRel::updates((int)$data['goods_id'], $spec_data['newMealList']);
            // 新增商品sku信息
            if($data['open_sale']==GoodsOpenSaleEnum::OPEN()->getKey()){
                GoodsSku::edit((int)$data['goods_id'], $spec_data['newSkuList']);
            }
            GoodsRentSku::edit((int)$data['goods_id'],  $spec_data['newRentSkuList']);

            Goods::where('id',$data['goods_id'])->update([
                'open_stock'=>$data['specData']['open_stock']??0,'open_sku_no'=>$data['specData']['open_sku_no']??0,'open_line_price'=>$data['specData']['open_line_price']??0
            ]);
            return true;
        });


    }

    //编辑商品基础信息
    protected function EditGoodsData($data){

        $goods = $this->where([['id',$data['goods_id']]])->select('id','status','ischeck')->first();
        $goods = $goods ? $goods->toArray() : array();
        if(empty($goods)){
            return ['status'=>CommonService::HTTP_CODE_FAIL,'msg'=>'商品不存在','data'=>[]];
        }
        unset($data['goods_id']);
        GoodsDepict::EditGoodsDepict($goods['id'],$data['carousel_img'],$data['goods_content']);

        unset($data['carousel_img']);
        unset($data['goods_content']);
        unset($data['specData']);
        $pid=GoodsClass::query()->where('id',$data['category_id'])->value('pid');
        if($pid>0){
            $data['subclass_id']=$data['category_id'];
            $data['category_id']=$pid;
        }else{
            $data['subclass_id']=0;
        }

        $this->where('id',$goods['id'])->update($data);


        return ['status'=>CommonService::HTTP_CODE_SUCCESS,'msg'=>'修改成功','data'=>['goods_id'=>$goods['id']]];
    }

    protected function DealGoodsMealSpecData($data,$goods){
        // 验证规格值是否合法
        if (!is_array($data['specData']['specList'])){
            throw new ApiException('规格数据不合法');
        }
        if (!is_array($data['specData']['mealList'])){
            throw new ApiException('套餐数据不合法');
        }
        if (!is_array($data['specData']['rentSkuList'])){
            throw new ApiException('套餐数据不合法');
        }
        if(!isset($data['specData']['rentSkuList'][0]['rentPrices'])||!is_array($data['specData']['rentSkuList'][0]['rentPrices'])){
            throw new ApiException('套餐数据不合法');
        }


        $business_type=Goods::where('id',$data['goods_id'])->Value('business_type');
        GoodsRentSpec::checkSpecData($data['specData']['specList']);
        GoodsRentMeal::checkMealData($data['specData']['mealList'],$business_type);
        GoodsRentSku::checkSkuData($data['specData']['rentSkuList']);

        // 生成多规格数据 (携带id)
        $spec_data=[];
        $spec_data['newSpecList'] = GoodsRentSpec::getNewSpecList($data['specData']['specList']);
        $spec_data['newMealList'] = GoodsRentMeal::getNewMealList($data['specData']['mealList']);

        // 生成skuList (携带goods_sku_id)
        $spec_data['newRentSkuList'] = GoodsRentSku::getNewSkuList($spec_data['newSpecList'],$spec_data['newMealList'], $data['specData']['rentSkuList']);

        if($goods['open_sale']==GoodsOpenSaleEnum::OPEN()->getKey()||(isset($data['open_sale'])&&$data['open_sale']==GoodsOpenSaleEnum::OPEN()->getKey())){
            $spec_data['newSkuList'] = GoodsSku::getNewSkuList($spec_data['newSpecList'],$data['specData']['skuList']);
        }
        // 更新商品
        return  DB::transaction(function () use ($data,$spec_data) {
            // 新增商品与规格关联
            GoodsRentSpecRel::updates((int)$data['goods_id'], $spec_data['newSpecList']);
            GoodsRentMealRel::updates((int)$data['goods_id'], $spec_data['newMealList']);
            // 新增商品sku信息
            GoodsRentSku::edit((int)$data['goods_id'],  $spec_data['newRentSkuList']);
            if(isset($spec_data['newSkuList'])){
                GoodsSku::edit((int)$data['goods_id'], $spec_data['newSkuList']);
            }

            Goods::where('id',$data['goods_id'])->update([
                'open_stock'=>$data['specData']['open_stock']??0,'open_sku_no'=>$data['specData']['open_sku_no']??0,'open_line_price'=>$data['specData']['open_line_price']??0
            ]);
            return true;
        });


    }

    /**
     * 下架
     */
    protected function ItemDownShelf($goods_id,$member_id){
        $goods = $this->where([['id',$goods_id],['member_id',$member_id],['is_delete',GoodsService::GOODS_NO_DELETE_STATUS]])
            ->select('id','status','ischeck','activity_type')->first();
        $goods = $goods ? $goods->toArray() : [];
        if(!empty($goods)){
            if(($goods['status'] == GoodsService::GOODS_STATUS_PUT || $goods['status'] == GoodsService::GOODS_STATUS_OFF_REFUSE)){
                if(!empty($goods['activity_type'])){
                    $res = $this->where('id',$goods_id)->update(['status'=>GoodsService::GOODS_STATUS_APPLY_OFF,'is_shelf_check'=>GoodsService::GOODS_SHELF_CHECK,'update_time'=>time()]);
                    $operation_explain = '商品申请下架';
                    $operation_type = 1;
                }else{
                    $res = $this->where('id',$goods_id)->update(['status'=>GoodsService::GOODS_STATUS_OFF,'is_shelf_check'=>GoodsService::GOODS_NO_SHELF_CHECK,'update_time'=>time()]);
                    $operation_explain = '商品下架';
                    $operation_type = 2;
                }
                if($res){
                    return ['status'=>CommonService::HTTP_CODE_SUCCESS,'msg'=>'操作成功','data'=>['operation_explain'=>$operation_explain,'operation_type'=>$operation_type]];
                }else{
                    return ['status'=>CommonService::HTTP_CODE_FAIL,'msg'=>'操作失败'];
                }
            }else{
                return ['status'=>CommonService::HTTP_CODE_FAIL,'msg'=>'已上架商品才能操作下架'];
            }
        }else{
            return ['status'=>CommonService::HTTP_CODE_FAIL,'msg'=>'商品不存在'];
        }
    }


    /**
     * 上架
     */
    protected function GoodsGrounding($goods_id,$member_id){
        $goods = $this->where([['id',$goods_id],['member_id',$member_id],['is_delete',GoodsService::GOODS_NO_DELETE_STATUS]])
            ->select('id','status','ischeck','activity_type')->first();
        $goods = $goods ? $goods->toArray() : [];
        if(!empty($goods)){
            if($goods['ischeck'] == GoodsService::GOODS_CHECK_STATUS_CHECKED && ($goods['status'] == GoodsService::GOODS_STATUS_OFF || $goods['status'] == GoodsService::GOODS_STATUS_VIOLATION_OFF)){
                $data['min_price'] = GoodsSpec::GetMinPrice($goods_id);
                $data['min_lease_term'] = GoodsSetmeal::getGoodsMinLeaseTerm($goods_id);
                $data['status'] = GoodsService::GOODS_STATUS_PUT;
                $data['is_huabei'] = GoodsSetmeal::getGoodsHuabei($goods_id);
                $data['update_time'] = time();
                $res = $this->where('id',$goods_id)->update($data);
                if($res){
                    return ['status'=>CommonService::HTTP_CODE_SUCCESS,'msg'=>'操作成功'];
                }else{
                    return ['status'=>CommonService::HTTP_CODE_FAIL,'msg'=>'操作失败'];
                }
            }else{
                return ['status'=>CommonService::HTTP_CODE_FAIL,'msg'=>'商品状态有误'];
            }
        }else{
            return ['status'=>CommonService::HTTP_CODE_FAIL,'msg'=>'商品不存在'];
        }
    }

    /**
     * 删除商品
     */
    protected function GoodsDelete($goods_id,$member_id){
        $goods = $this->where([['id',$goods_id],['member_id',$member_id],['is_delete',GoodsService::GOODS_NO_DELETE_STATUS]])
            ->select('id','status','ischeck')->first();
        $goods = $goods ? $goods->toArray() : [];
        if(!empty($goods)){
            if($goods['ischeck'] == GoodsService::GOODS_CHECK_STATUS_CHECKED && ($goods['status'] == GoodsService::GOODS_STATUS_PUT) || $goods['status'] == GoodsService::GOODS_STATUS_APPLY_OFF || $goods['status'] == GoodsService::GOODS_STATUS_OFF_REFUSE){ //已审核  上架中  不能删除
                return ['status'=>CommonService::HTTP_CODE_FAIL,'msg'=>'商品上架中不能操作删除'];
            }
            $res = $this->where([['id',$goods_id],['member_id',$member_id],['is_delete',GoodsService::GOODS_NO_DELETE_STATUS]])->update(['is_delete'=>GoodsService::GOODS_DELETE_STATUS,'update_time'=>time()]);
            if($res){
                return ['status'=>CommonService::HTTP_CODE_SUCCESS,'msg'=>'操作成功'];
            }else{
                return ['status'=>CommonService::HTTP_CODE_FAIL,'msg'=>'操作失败'];
            }
        }else{
            return ['status'=>CommonService::HTTP_CODE_FAIL,'msg'=>'商品不存在'];
        }
    }

    /**
     * 提交审核
     */
    protected function SubmitReview($goods_id,$member_id){
        $goods = $this->where([['id',$goods_id],['member_id',$member_id],['is_delete',GoodsService::GOODS_NO_DELETE_STATUS]])
            ->select('id','status','ischeck')->first();
        $goods = $goods ? $goods->toArray() : [];
        if(!empty($goods)){
            if($goods['ischeck'] != GoodsService::GOODS_CHECK_STATUS_CHECKED){
                $res = $this->where([['id',$goods_id],['member_id',$member_id],['is_delete',GoodsService::GOODS_NO_DELETE_STATUS]])->update(['ischeck'=>GoodsService::GOODS_CHECK_STATUS_NO,'update_time'=>time()]);
                if($res){
                    return ['status'=>CommonService::HTTP_CODE_SUCCESS,'msg'=>'操作成功'];
                }else{
                    return ['status'=>CommonService::HTTP_CODE_FAIL,'msg'=>'操作失败'];
                }
            }else{
                return ['status'=>CommonService::HTTP_CODE_FAIL,'msg'=>'商品状态不支持该操作'];
            }
        }else{
            return ['status'=>CommonService::HTTP_CODE_FAIL,'msg'=>'商品不存在'];
        }
    }

    /**
     * 取消审核
     */
    protected function CancelReview($goods_id,$member_id){
        $goods = $this->where([['id',$goods_id],['member_id',$member_id],['is_delete',GoodsService::GOODS_NO_DELETE_STATUS]])
            ->select('id','status','ischeck')->first();
        $goods = $goods ? $goods->toArray() : [];
        if(!empty($goods)){
            if($goods['ischeck'] == GoodsService::GOODS_CHECK_STATUS_NO || $goods['status'] == GoodsService::GOODS_STATUS_APPLY_OFF ){
                if($goods['ischeck'] == GoodsService::GOODS_CHECK_STATUS_NO){
                    if($goods['status'] == 0){
                        $res = $this->where([['id',$goods_id],['member_id',$member_id],['is_delete',GoodsService::GOODS_NO_DELETE_STATUS]])->update(['ischeck'=>GoodsService::GOODS_CHECK_STATUS_DRAFT,'update_time'=>time()]);
                    }else{
                        $res = $this->where([['id',$goods_id],['member_id',$member_id],['is_delete',GoodsService::GOODS_NO_DELETE_STATUS]])->update(['ischeck'=>GoodsService::GOODS_CHECK_STATUS_NOT_SUBMIT,'update_time'=>time()]);
                    }
                }elseif($goods['status'] == GoodsService::GOODS_STATUS_APPLY_OFF){
                    $res = $this->where([['id',$goods_id],['member_id',$member_id],['is_delete',GoodsService::GOODS_NO_DELETE_STATUS]])->update(['status'=>GoodsService::GOODS_STATUS_PUT,'update_time'=>time()]);
                }
                if($res){
                    return ['status'=>CommonService::HTTP_CODE_SUCCESS,'msg'=>'操作成功'];
                }else{
                    return ['status'=>CommonService::HTTP_CODE_FAIL,'msg'=>'操作失败'];
                }
            }else{
                return ['status'=>CommonService::HTTP_CODE_FAIL,'msg'=>'商品状态不支持该操作'];
            }
        }else{
            return ['status'=>CommonService::HTTP_CODE_FAIL,'msg'=>'商品不存在'];
        }
    }


    /**
     * 批量删除草稿
     */
    protected function BatchDeleteDraft($goods_id,$member_id){
        foreach ($goods_id as $k=>$v){
            $goods = $this->where([['id',$v],['member_id',$member_id],['is_delete',GoodsService::GOODS_NO_DELETE_STATUS],['ischeck',GoodsService::GOODS_CHECK_STATUS_DRAFT]])->select('id','status','ischeck')->first();
            $goods = $goods ? $goods->toArray() : [];
            if(!empty($goods)){
                $this->where([['id',$v],['member_id',$member_id],['is_delete',GoodsService::GOODS_NO_DELETE_STATUS],['ischeck',GoodsService::GOODS_CHECK_STATUS_DRAFT]])->update(['is_delete'=>GoodsService::GOODS_DELETE_STATUS,'update_time'=>time()]);
            }
        }
        return ['status'=>CommonService::HTTP_CODE_SUCCESS,'msg'=>'操作成功'];
    }


    //审核商品列表
    protected function goodsCheckList($request){
        $pageSize = !empty($request['pageSize'])?$request['pageSize']:CommonService::PAGESIZE;
        if(!empty($request['goods_name'])){
            $where[] = ['g.title','like','%'.trim($request['goods_name']).'%'];
        }
        if(!empty($request['shop_name'])){
            $where[] = ['s.shopname','like','%'.trim($request['shop_name']).'%'];
        }
        if(!empty($request['check_status']) && in_array($request['check_status'],[GoodsService::GOODS_CHECK_STATUS_NO,GoodsService::GOODS_CHECK_STATUS_CHECKED,GoodsService::GOODS_CHECK_STATUS_REFUSE])){
            $check_where[] = ['g.ischeck',$request['check_status']];
        }else{
            $check_where[] = ['g.ischeck','>=',GoodsService::GOODS_CHECK_STATUS_NO];
        }
        if(!empty($request['create_time'])){
            $time_data = searchTime($request['create_time']);
            $begin_time = $time_data['begin_time'];
            $end_time = $time_data['end_time'];
            $where[] = ['g.update_time','>=',strtotime($begin_time)];
            $where[] = ['g.update_time','<=',strtotime($end_time)];
        }
        $where[] = ['g.is_delete',GoodsService::GOODS_NO_DELETE_STATUS];

        $list = $this->from('sp_goods_2 as g')->where($where)->where($check_where)
            ->leftjoin('sp_shop_user_2 as s','s.member_id','=','g.member_id')
            ->leftjoin('sp_category as c','c.id','=','g.category_id')
            ->select('g.id','g.title','g.imgurl','c.name as cate_name','g.ischeck','g.update_time','g.check_reason','s.shopname','g.activity_type')
            ->orderBy('g.goods_sort', 'asc')
            ->orderBy('g.id', 'desc')
            ->paginate($pageSize);

        unset($check_where);
        $check_where[] = ['g.ischeck','>=',GoodsService::GOODS_CHECK_STATUS_NO];
        $all_goods = $this->from('sp_goods_2 as g')->where($where)->where($check_where)
            ->leftjoin('sp_shop_user_2 as s','s.member_id','=','g.member_id')->leftjoin('sp_category as c','c.id','=','g.category_id')->count();
        unset($check_where);
        $check_where[] = ['g.ischeck',GoodsService::GOODS_CHECK_STATUS_NO];
        $nocheck_count = $this->from('sp_goods_2 as g')->where($where)->where($check_where)
            ->leftjoin('sp_shop_user_2 as s','s.member_id','=','g.member_id')->leftjoin('sp_category as c','c.id','=','g.category_id')->count();
        unset($check_where);
        $check_where[] = ['g.ischeck',GoodsService::GOODS_CHECK_STATUS_CHECKED];
        $checked_count = $this->from('sp_goods_2 as g')->where($where)->where($check_where)
            ->leftjoin('sp_shop_user_2 as s','s.member_id','=','g.member_id')->leftjoin('sp_category as c','c.id','=','g.category_id')->count();
        unset($check_where);
        $check_where[] = ['g.ischeck',GoodsService::GOODS_CHECK_STATUS_REFUSE];
        $refuse_count = $this->from('sp_goods_2 as g')->where($where)->where($check_where)
            ->leftjoin('sp_shop_user_2 as s','s.member_id','=','g.member_id')->leftjoin('sp_category as c','c.id','=','g.category_id')->count();

        $list = $list ? $list->toArray() : array();
        $list['count']['all_goods'] = $all_goods;
        $list['count']['nocheck_count'] = $nocheck_count;
        $list['count']['checked_count'] = $checked_count;
        $list['count']['refuse_count'] = $refuse_count;
        return $list;
    }

    //下架审核商品列表
    protected function goodsShelfCheckList($request){
        $pageSize = !empty($request['pageSize'])?$request['pageSize']:CommonService::PAGESIZE;
        if(!empty($request['goods_name'])){
            $where[] = ['g.title','like','%'.trim($request['goods_name']).'%'];
        }
        if(!empty($request['shop_name'])){
            $where[] = ['s.shopname','like','%'.trim($request['shop_name']).'%'];
        }
        if(!empty($request['check_status']) && in_array($request['check_status'],[GoodsService::GOODS_STATUS_OFF,GoodsService::GOODS_STATUS_APPLY_OFF,GoodsService::GOODS_STATUS_OFF_REFUSE])){
            $check_where[] = ['g.status',$request['check_status']];
            $check_where[] = ['g.is_shelf_check',GoodsService::GOODS_SHELF_CHECK];
        }else{
            $check_where[] = ['g.status','>=',GoodsService::GOODS_STATUS_OFF];
            $check_where[] = ['g.status','<=',GoodsService::GOODS_STATUS_OFF_REFUSE];
            $check_where[] = ['g.is_shelf_check',GoodsService::GOODS_SHELF_CHECK];
        }
        if(!empty($request['create_time'])){
            $time_data = searchTime($request['create_time']);
            $begin_time = $time_data['begin_time'];
            $end_time = $time_data['end_time'];
            $where[] = ['g.update_time','>=',strtotime($begin_time)];
            $where[] = ['g.update_time','<=',strtotime($end_time)];
        }
        $where[] = ['g.is_delete',GoodsService::GOODS_NO_DELETE_STATUS];

        $list = $this->from('sp_goods_2 as g')->where($where)->where($check_where)
            ->leftjoin('sp_shop_user_2 as s','s.member_id','=','g.member_id')
            ->leftjoin('sp_category as c','c.id','=','g.category_id')
            ->select('g.id','g.title','g.imgurl','c.name as cate_name','g.status','g.update_time','g.check_reason','s.shopname','g.activity_type')
            ->orderBy('g.goods_sort', 'asc')
            ->orderBy('g.id', 'desc')
            ->paginate($pageSize);

        unset($check_where);
        $check_where[] = ['g.status','>=',GoodsService::GOODS_STATUS_OFF];
        $check_where[] = ['g.status','<=',GoodsService::GOODS_STATUS_OFF_REFUSE];
        $check_where[] = ['g.is_shelf_check',GoodsService::GOODS_SHELF_CHECK];
        $all_goods = $this->from('sp_goods_2 as g')->where($where)->where($check_where)
            ->leftjoin('sp_shop_user_2 as s','s.member_id','=','g.member_id')->leftjoin('sp_category as c','c.id','=','g.category_id')->count();
        unset($check_where);
        $check_where[] = ['g.status',GoodsService::GOODS_STATUS_APPLY_OFF];
        $check_where[] = ['g.is_shelf_check',GoodsService::GOODS_SHELF_CHECK];
        $nocheck_count = $this->from('sp_goods_2 as g')->where($where)->where($check_where)
            ->leftjoin('sp_shop_user_2 as s','s.member_id','=','g.member_id')->leftjoin('sp_category as c','c.id','=','g.category_id')->count();
        unset($check_where);
        $check_where[] = ['g.status',GoodsService::GOODS_STATUS_OFF];
        $check_where[] = ['g.is_shelf_check',GoodsService::GOODS_SHELF_CHECK];
        $checked_count = $this->from('sp_goods_2 as g')->where($where)->where($check_where)
            ->leftjoin('sp_shop_user_2 as s','s.member_id','=','g.member_id')->leftjoin('sp_category as c','c.id','=','g.category_id')->count();
        unset($check_where);
        $check_where[] = ['g.status',GoodsService::GOODS_STATUS_OFF_REFUSE];
        $check_where[] = ['g.is_shelf_check',GoodsService::GOODS_SHELF_CHECK];
        $refuse_count = $this->from('sp_goods_2 as g')->where($where)->where($check_where)
            ->leftjoin('sp_shop_user_2 as s','s.member_id','=','g.member_id')->leftjoin('sp_category as c','c.id','=','g.category_id')->count();

        $list = $list ? $list->toArray() : array();
        $list['count']['all_goods'] = $all_goods;
        $list['count']['nocheck_count'] = $nocheck_count;
        $list['count']['checked_count'] = $checked_count;
        $list['count']['refuse_count'] = $refuse_count;
        return $list;
    }

    //小程序检测商品状态
    protected function checkGoodsStatus($goods_id){
        $goods = $this->where([['id',$goods_id],['status',GoodsService::GOODS_STATUS_PUT],['is_delete',GoodsService::GOODS_NO_DELETE_STATUS]])
            ->select('member_id','title','imgurl','pay_type','new_grade','convey_type','contract_type','sign_num','category_id','is_insurance')->first();
        $goods = $goods ? $goods->toArray() : [];
        $goods['pay_type'] = '1';
        return $goods;
    }


    protected function apiGetGoodsList($member_id){
        $goods = $this->from('sp_goods_2 as g')->where([['g.member_id',$member_id],['g.is_delete',GoodsService::GOODS_NO_DELETE_STATUS]])
            ->leftjoin('sp_shop_user_2 as s','s.member_id','=','g.member_id')
            ->leftjoin('sp_category as c','c.id','=','g.category_id')
            ->select('g.id','g.title','g.status','g.displayorder','g.imgurl','c.name as cate_name','g.ischeck','g.create_time','g.check_reason','s.shopname','g.activity_type','g.checked_status')
            ->orderBy('g.goods_sort', 'asc')
            ->orderBy('g.id', 'desc')
            ->get();
        $goods = $goods ? $goods->toArray() : [];
        return $goods;
    }



    public function goods_rent_sku()
    {
        return $this->hasMany(GoodsRentSku::class,'goods_id','id');
    }
    public function goods_sku()
    {
        return $this->hasMany(GoodsSku::class,'goods_id','id');
    }

}
